package com.zly.app.service;

import com.zly.app.dao.AppCategoryDao;
import com.zly.app.entity.AppCategory;
import com.zly.app.vo.CategoryTreeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class AppCategoryService {

    @Autowired
    AppCategoryDao appCategoryDao;

    public CategoryTreeVo tree(){
        List<CategoryTreeVo> voList  =  new ArrayList<>();

        List<AppCategory> list = appCategoryDao.queryAll(new AppCategory());

        for (AppCategory category : list){
            CategoryTreeVo vo = new CategoryTreeVo();
            BeanUtils.copyProperties(category,vo);
            voList.add(vo);
        }

        CategoryTreeVo tree = new CategoryTreeVo();
        for (CategoryTreeVo categoryTreeVo : voList) {
            if (categoryTreeVo.getParentid()==null) {
                tree = findChildren(categoryTreeVo, voList);
            }
        }
        return tree;
    }


    private  CategoryTreeVo findChildren(CategoryTreeVo vo, List<CategoryTreeVo> voList){
        vo.setChildren(new ArrayList<>());
        for (CategoryTreeVo categoryTreeVo : voList) {
            if (vo.getId().equals(categoryTreeVo.getParentid())){
                vo.getChildren().add(categoryTreeVo);
                findChildren(categoryTreeVo,voList);
            }
        }
        return vo;
    }
}
